#!/bin/bash

# Android 应用构建脚本

echo "=== WeChat Android 应用构建脚本 ==="
echo ""

# 检查 Java
if ! command -v java &> /dev/null; then
    echo "❌ 错误: 未找到 Java，请先安装 JDK"
    exit 1
fi

echo "✅ Java 版本:"
java -version
echo ""

# 检查 Android SDK
if [ -z "$ANDROID_HOME" ]; then
    if [ -d "$HOME/Library/Android/sdk" ]; then
        export ANDROID_HOME="$HOME/Library/Android/sdk"
        echo "✅ 找到 Android SDK: $ANDROID_HOME"
    else
        echo "❌ 错误: 未找到 Android SDK"
        echo "请设置 ANDROID_HOME 环境变量或安装 Android SDK"
        exit 1
    fi
else
    echo "✅ Android SDK: $ANDROID_HOME"
fi
echo ""

# 检查或创建 gradle-wrapper.jar
if [ ! -f "gradle/wrapper/gradle-wrapper.jar" ]; then
    echo "⚠️  未找到 gradle-wrapper.jar"
    echo "请使用以下方法之一："
    echo ""
    echo "方法 1: 使用 Android Studio"
    echo "  1. 在 Android Studio 中打开此项目"
    echo "  2. Android Studio 会自动下载 Gradle wrapper"
    echo "  3. 然后就可以构建和运行了"
    echo ""
    echo "方法 2: 手动下载"
    echo "  curl -L -o gradle/wrapper/gradle-wrapper.jar \\"
    echo "    https://repo1.maven.org/maven2/org/gradle/gradle-wrapper/8.2/gradle-wrapper-8.2.jar"
    echo ""
    exit 1
fi

echo "✅ 找到 gradle-wrapper.jar"
echo ""

# 检查设备
echo "检查连接的设备..."
if command -v adb &> /dev/null; then
    DEVICES=$(adb devices | grep -v "List" | grep "device$" | wc -l | tr -d ' ')
    if [ "$DEVICES" -gt 0 ]; then
        echo "✅ 找到 $DEVICES 个设备:"
        adb devices
    else
        echo "⚠️  未找到连接的设备"
        echo "请连接 Android 设备或启动模拟器"
    fi
else
    echo "⚠️  adb 未找到，无法检查设备"
    echo "adb 通常位于: $ANDROID_HOME/platform-tools/adb"
fi
echo ""

# 构建选项
echo "请选择操作:"
echo "1. 构建 Debug APK"
echo "2. 构建并安装到设备"
echo "3. 构建并运行应用"
echo "4. 清理构建"
echo "5. 仅检查项目配置"
echo ""
read -p "请输入选项 (1-5): " choice

case $choice in
    1)
        echo ""
        echo "🔨 开始构建 Debug APK..."
        ./gradlew assembleDebug
        if [ $? -eq 0 ]; then
            echo ""
            echo "✅ 构建成功！"
            echo "APK 位置: app/build/outputs/apk/debug/app-debug.apk"
        fi
        ;;
    2)
        echo ""
        echo "🔨 开始构建并安装..."
        ./gradlew installDebug
        if [ $? -eq 0 ]; then
            echo ""
            echo "✅ 安装成功！"
        fi
        ;;
    3)
        echo ""
        echo "🔨 开始构建并运行..."
        ./gradlew installDebug && adb shell am start -n com.wechat.app/.MainActivity
        if [ $? -eq 0 ]; then
            echo ""
            echo "✅ 应用已启动！"
        fi
        ;;
    4)
        echo ""
        echo "🧹 清理构建..."
        ./gradlew clean
        ;;
    5)
        echo ""
        echo "📋 项目配置检查:"
        echo "  包名: com.wechat.app"
        echo "  最低 SDK: 24 (Android 7.0)"
        echo "  目标 SDK: 34 (Android 14)"
        echo "  编译 SDK: 34"
        ;;
    *)
        echo "❌ 无效选项"
        exit 1
        ;;
esac

